package org.ajax.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.ajax.entity.Student;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 模拟 DAO - 查询学生列表 - 转换为 json 字符串 - 响应到客户端页面中
 *
 * @author ZQX
 * @date 2024-11-18
 */
@WebServlet("/list.do")
public class ListDataServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求、响应编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 第一：模拟 DAO ，查询数据列表 - List集合
        List<Student> list = new ArrayList<>();

        Student zs = new Student("张三", 18, 99, new Date());
        Student ls = new Student("李四", 28, 89, new Date());
        Student ww = new Student("王五", 38, 79, new Date());

        list.add(zs);
        list.add(ls);
        list.add(ww);

        // 第二：实例化 Gson 对象，并设置日期时间格式
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd").create();

        // 第三：序列化
        String json = gson.toJson(list);

        // 第四：响应客户端
        PrintWriter out = resp.getWriter();

        out.println(json);

        out.flush();
        out.close();

    }
}
